# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify

from modules.chat import chat

app = Flask(__name__)


@app.route('/process_post', methods=['POST'])
def process_post():
    # 检查auth头字段的值是否为'abcdef'
    auth_header = request.headers.get('auth')
    if auth_header != 'passwd':
        return 'Unauthorized', 401

    # 解析JSON报文
    try:
        data = request.get_json()
        text_content = data.get('text')
        if text_content is not None:
            response = chat(text_content)
            return response, 200, {'Content-Type': 'text/html'}
        else:
            return 'Missing "text" field in JSON', 400
    except Exception as e:
        return str(e), 400


def listen_http(port):
    app.run(host='0.0.0.0', port=port)
